package com.example.demo2.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * @Author: Robin
 * @Description: 异步注解@Async、线程池ThreadPoolTaskExecutor调用、定时Scheduled 测试
 */
@Component
public class TestAsync {

    @Autowired
    TaskPoolConfig taskPoolConfig;

    /**
     * 注解方式异步调用方法执行业务逻辑
     * @Async注解默认使用spring自带的线程池执行异步，这里指定了使用“taskExecutor”线程池。
     */
    //@Async                    //使用spring自带的线程池执行异步
    @Async("taskExecutor")      //这里指定了使用“taskExecutor”线程池
    public void test2 (){
        try {
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello world2");
    }


    public void test3(){
        /**
         * 用线程池调用的方式开启一个新线程执行业务逻辑
         */
        taskPoolConfig.taskExecutor().execute(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        });
    }

    @Scheduled(cron="*/3 * * * * ?")
    public void test4(){
        System.out.println("开始执行test4 function");
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test4 结束");
    }

    @Scheduled(cron="*/4 * * * * ?")
    public void test5(){
        System.out.println("开始执行test5  function" );
        System.out.println("test5  结束");
    }




}
